import React, { useRef, useState, useEffect } from "react";
import { Modal, Spin, message } from "antd";
import { LeftOutlined, RightOutlined, DragOutlined, DeleteOutlined, ArrowDownOutlined, ShareAltOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import styled from "styled-components";
import { useNavigate } from "react-router-dom";
import * as oss from "../../services/oss";
import store from "../../utils/store";
import { alertError, loading, noti, notiError, notiOK } from "../../utils/antd-helper";
import { verifyEmailAndSendBindCode, verifyEmail } from "../../services/graphql";
import { checkLogin } from "../../services/user";
import copy from "copy-to-clipboard";
import "./p-box.less";
let inputValues = {
	email: "",
	vcode: "",
	hasSend: false
};

function Main({ className }) {
	const navigate = useNavigate();
	const [showBindBox, setShowBindBox] = useState(false);
	const [isLoading, setIsLoading] = useState(false);
	const [account, setAccount] = useState();
	const [email, setEmail] = useState();
	const [remainSec, setRemainSec] = useState(0);
	const countDown = async s => {
		for (let i = 0; i < s; i++) {
			setRemainSec(s - i - 1);
			await sleep(1);
		}
	};
	const sleep = s => {
		return new Promise((resolve, reject) => {
			setTimeout(function () {
				resolve();
			}, s * 1000);
		});
	};

	const init = async () => {
		let acc = oss.getAccount();
		if (!acc) {
			setIsLoading(false);
			console.log("unlogin,try after 3s");
			setTimeout(init, 3000);
			return;
		}
		setAccount(acc);
		// setIsLoading(true);
		await oss.queryBalance();
		await oss.territories();
		// setIsLoading(false);
	};
	useEffect(() => {
		let isLogin = checkLogin(navigate);
		if (isLogin) {
			init();
			let id = store.get("identity");
			let iden = store.get("email-" + id);
			if (iden) {
				setEmail(iden);
			} else {
				let acc = store.get('account');
				if (acc.email) {
					setEmail(acc.email);
				}
			}
		}
	}, []);
	const onShowBindBox = () => {
		setShowBindBox(true);
	};
	const onLogout = () => {
		store.clear();
		navigate("/");
		window.location.reload();
	};
	const onInputEmail = e => {
		inputValues.email = e.target.value;
	};
	const onInputVCode = e => {
		inputValues.vcode = e.target.value;
	};
	const onSendVCode = async () => {
		if (!inputValues.email || !inputValues.email.includes("@") || inputValues.email.length < 5) {
			return notiError("Email format error");
		}
		loading("Loading...");
		let ret = await verifyEmailAndSendBindCode(inputValues.email);
		loading();
		if (ret.msg == 'ok' && ret.data.initiateEmailBind) {
			notiOK("Verify code send success");
			inputValues.hasSend = true;
		} else {
			inputValues.hasSend = false;
			alertError(ret.msg);
		}
		await countDown(60);
	};
	const onConfirm = async () => {
		if (!inputValues.email || !inputValues.email.includes("@") || inputValues.email.length < 5) {
			return notiError("Email format error");
		}
		if (!inputValues.hasSend) {
			return notiError("Send verify code please");
		}
		if (!inputValues.vcode || inputValues.vcode.length < 4) {
			return notiError("Verify code format error");
		}
		loading("Loading...");
		let ret = await verifyEmail(inputValues.vcode);
		loading();
		if (ret.msg == 'ok' && ret.data.bindEmail) {
			notiOK("Email bind success");
			let id = store.get("identity");
			store.set("email-" + id, inputValues.email);
			setEmail(inputValues.email);
			setShowBindBox(false);
		} else {
			alertError(ret.msg);
		}
	};
	const onCopy = () => {
		copy(account?.address);
		message.success("Copied");
	};
	return (
		<div className={className}>
			<Spin spinning={isLoading}>
				<div className="con">
					<div className="banner">
						<div className="t1">Balance</div>
						<div className="t2">
							<img width={20} height={18} src={process.env.PUBLIC_URL + "/img/icon_cess2.png"} />
							<span>{account?.balance_str}</span>
						</div>
						<div className="t3" onClick={onCopy}>
							{account?.address}&nbsp;
							<img width={14} src={process.env.PUBLIC_URL + "/img/copy.png"} />
						</div>
						<div className="btn" onClick={onLogout}>
							Logout
						</div>
					</div>
					<div className="cotent">
						<div className="box box-left">
							<div className="bleft">
								<img width={36} height={36} src={process.env.PUBLIC_URL + "/img/email.png"} />
							</div>
							<div className="bcon">
								<span>{email || "unbound"}</span>
								<label>Email</label>
							</div>
							{email ? (
								<div className="btn disable">
									<img width={14} height={14} src={process.env.PUBLIC_URL + "/img/edit.png"} />
									<span>Bind</span>
								</div>
							) : (
								<div className="btn enable" onClick={onShowBindBox}>
									<img width={14} height={14} src={process.env.PUBLIC_URL + "/img/edit.png"} />
									<span>Bind</span>
								</div>
							)}
						</div>
						<div className="box box-right">More functions is coming soon !</div>
					</div>
				</div>
			</Spin>
			<Modal width={800} open={showBindBox} footer={null} onCancel={() => setShowBindBox(false)}>
				<div className="p-box">
					<div className="title">Bind Email</div>
					<div className="intput">
						<input type="email" onInput={onInputEmail} onKeyUp={onInputEmail} onChange={onInputEmail} placeholder="Enter your email" />
						{remainSec < 1 ? (
							<span className="send-btn send-btn-enable" onClick={onSendVCode}>
								send
							</span>
						) : (
							<span className="send-btn send-btn-disable">{remainSec}s</span>
						)}
					</div>
					<div className="intput">
						<input type="text" onInput={onInputVCode} onChange={onInputVCode} onKeyUp={onInputVCode} placeholder="Enter the code" />
					</div>
					<div className="btn-box">
						<span className="btn btn-p" onClick={onConfirm}>
							Confirm
						</span>
						<span className="btn btn-d" onClick={() => setShowBindBox(false)}>
							Cancel
						</span>
					</div>
				</div>
			</Modal>
		</div>
	);
}

export default styled(Main)`
	display: block;
	.con {
		display: flex;
		flex-direction: column;
		width: 800px;
		margin: 0px auto;
	}
	.banner {
		width: 100%;
		height: 170px;
		margin: 20px 0;
		background-image: url("/img/account-bg.svg");
		background-repeat: no-repeat;
		background-size: cover;
		border-radius: 20px;
		background-position: center;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #000;
		position: relative;
		font-size: 14px;
		top: 0;
		.t1 {
			margin-top: 20px;
		}
		.t2 {
			font-size: 28px;
			height: 30px;
			line-height: 30px;
			margin: 29px 0;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			img {
				margin-right: 10px;
				margin-top: 4px;
			}
		}
		.t3 {
			color: #000;
			cursor: copy;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
		}
		.btn {
			position: absolute;
			top: 10px;
			right: 10px;
			height: 30px;
			width: 60px;
			display: block;
			overflow: hidden;
			text-align: center;
			font-size: 12px;
			line-height: 30px;
			background-color: rgba(250, 250, 250, 0.8);
			border-radius: 6px;
			cursor: pointer;
		}
		.btn:hover {
			background-color: #fff;
		}
	}
	.cotent {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		font-size: 16px;
		color: #000;
		.box {
			width: 49.5%;
			height: 100px;
			border-radius: 20px;
			background-color: rgba(240, 240, 240, 1);
		}
		.box-left {
			display: flex;
			flex-direction: row;
			align-items: center;
			.bleft {
				width: 88px;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				img {
					width: 36px;
					height: 36px;
				}
			}
			.bcon {
				display: flex;
				flex-direction: column;
				flex: 1;
				span {
					line-height: 30px;
				}
				label {
					line-height: 30px;
					color: #aeaeae;
				}
			}
			.btn {
				width: 54px;
				height: 30px;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				margin-right: 19px;
				border-radius: 6px;
				padding: 0 10px;
				font-size: 14px;
				img {
					width: 14px;
					margin-right: 10px;
				}
				span {
					color: #fff;
				}
			}
			.enable {
				cursor: pointer;
				background-color: rgba(51, 51, 51, 1);
			}
			.enable:hover {
				background-color: rgba(81, 81, 81, 1);
			}
			.disable {
				cursor: not-allowed;
				background-color: rgba(189, 189, 189, 1);
			}
		}
		.box-right {
			display: block;
			overflow: hidden;
			text-align: center;
			line-height: 100px;
		}
	}
`;
